package com.shengqin.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shengqin.common.pojo.CommonPage;
import com.shengqin.common.pojo.CommonResult;
import com.shengqin.config.CommonException;
import com.shengqin.entity.Classes;
import com.shengqin.entity.School;
import com.shengqin.entity.Student;
import com.shengqin.service.IClassesService;
import com.shengqin.service.IStudentService;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 班级信息 前端控制器
 * </p>
 *
 * @author Rui.Zhou
 * @since 2023-12-05
 */
@RestController
@RequestMapping("/admin/v1/classes")
public class ClassesController {
    @Resource
    private IClassesService classesService;
    @Resource
    private IStudentService studentService;


    @PostMapping("save")
    public CommonResult<Boolean> onSave(@RequestBody Classes classes){
        if(classes.getId() == null){
            Classes classesByName = classesService.getByGradeAndName(classes.getSchoolId(),classes.getGradeId(),classes.getName());
            if(classesByName != null){
                throw new CommonException("班级名称已存在");
            }
            classes.setCreateTime(LocalDateTime.now());
        }else{
            Classes oldClasses = classesService.getById(classes.getId());
            if(!oldClasses.getName().equals(classes.getName())){
                Classes classesByName = classesService.getByGradeAndName(classes.getSchoolId(),classes.getGradeId(),classes.getName());
                if(classesByName != null){
                    throw new CommonException("班级名称已存在");
                }
            }
        }
        return CommonResult.data(classesService.saveOrUpdate(classes));
    }


    @PostMapping("delete")
    public CommonResult<Boolean> onDelete(@RequestBody Classes classes){
        List<Student> studentList = studentService.listByClassesId(classes.getId());
        if(!CollectionUtils.isEmpty(studentList)){
            throw new CommonException("该班级有学生数据，无法删除");
        }
        return CommonResult.data(classesService.removeById(classes.getId()));
    }

    @PostMapping("page")
    public CommonResult<Page<Classes>> getPage(@RequestBody CommonPage<Classes> pageParam){
        Page<Classes> classesPage = classesService.getPage(pageParam);
        buildRecords(classesPage.getRecords());
        return CommonResult.data(classesPage);
    }

    private void buildRecords(List<Classes> records) {
        if(!CollectionUtils.isEmpty(records)){
            List<Integer> classesIds = records.stream().map(Classes::getId).collect(Collectors.toList());
            List<Student> studentList = studentService.listByClassesIds(classesIds);
            Map<Integer,List<Student>> studentMap = studentList.stream().collect(Collectors.groupingBy(Student::getClassesId));
            records.forEach(rec -> {
                List<Student> students = studentMap.getOrDefault(rec.getId(),null);
                if(!CollectionUtils.isEmpty(students)){
                    Map<String,List<Student>> studentSexMap = students.stream().collect(Collectors.groupingBy(Student::getSex));
                    rec.setStudentMaleCount(studentSexMap.getOrDefault("1",new ArrayList<>()).size());
                    rec.setStudentFemaleCount(studentSexMap.getOrDefault("2",new ArrayList<>()).size());
                }
                rec.setStudentCount(CollectionUtils.isEmpty(students) ? 0 : students.size());
            });
        }
    }
}
